package com.yitong.equipment.ui.mall

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.yitong.equipment.R
import com.yitong.equipment.base.BaseActivity
import com.yitong.equipment.databinding.ActivityMallAllClassifyBinding
import com.yitong.equipment.entity.other.CategoryOneArrayBean
import com.yitong.equipment.entity.other.SortBean
import com.yitong.equipment.interf.CheckListener
import com.yitong.equipment.ui.adapter.MallAllClassifyTitleAdapter
import com.yitong.equipment.ui.viewmodel.MallAllClassifyViewModel
import com.yitong.equipment.view.ItemHeaderDecoration
import java.io.IOException
import java.util.ArrayList


class MallAllClassifyActivity : BaseActivity<MallAllClassifyViewModel, ActivityMallAllClassifyBinding>(), CheckListener {
    private val mallAllClassifyTitleAdapter: MallAllClassifyTitleAdapter by lazy { MallAllClassifyTitleAdapter(arrayListOf()) }
    private lateinit var mSortBean: SortBean
    private lateinit var mallAllClassifyFragment: MallAllClassifyFragment
    private lateinit var linearLayoutManager: LinearLayoutManager

    //点击左边某一个具体的item的位置
    private var targetPosition = 0

    private var isMoved = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mall_all_classify)
        initView()
        initData()
    }


    private fun initView() {
        linearLayoutManager = LinearLayoutManager(this)
        bindingView.recycleView.layoutManager = linearLayoutManager
        val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        bindingView.recycleView.addItemDecoration(decoration)
        bindingView.recycleView.adapter = mallAllClassifyTitleAdapter
        mallAllClassifyTitleAdapter.setOnItemClickListener { adapter, view, position ->
            if (mallAllClassifyFragment != null) {
                isMoved = true
                targetPosition = position
                setChecked(position, true)
            }
        }
    }

    private fun initData() {
        //获取asset目录下的资源文件
        val assetsData = getAssetsData("sort.json")
        val gson = Gson()
        mSortBean = gson.fromJson(assetsData, SortBean::class.java)
        LogUtils.dTag("mSortBean",mSortBean.toString())
        val categoryOneArray: MutableList<CategoryOneArrayBean> = mSortBean.categoryOneArray!!

        val list: MutableList<String> = ArrayList()
        //初始化左侧列表数据
        for (i in categoryOneArray.indices) {
            list.add(categoryOneArray[i].name!!)
        }
        mallAllClassifyTitleAdapter.setList(list)
        createFragment()
    }

    private fun createFragment() {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        mallAllClassifyFragment = MallAllClassifyFragment()
        val bundle = Bundle()
        bundle.putParcelableArrayList("right", mSortBean.categoryOneArray)
        mallAllClassifyFragment.arguments = bundle
        mallAllClassifyFragment.setListener(this)
        fragmentTransaction.add(R.id.all_fragment, mallAllClassifyFragment)
        fragmentTransaction.commit()
    }

    private fun getAssetsData(path: String): String? {
        var result: String? = ""
        return try {
            val mAssets = assets.open(path)
            val buffer = ByteArray(mAssets.available())
            mAssets.read(buffer)
            mAssets.close()
            result = String(buffer)
            result
        } catch (e: IOException) {
            e.printStackTrace()
            result
        }
    }


    override fun check(position: Int, isScroll: Boolean) {
        setChecked(position, isScroll)
    }

    private fun setChecked(position: Int, isLeft: Boolean) {
        Log.d("p-------->", position.toString())
        if (isLeft) {
            mallAllClassifyTitleAdapter.setCheckedPosition(position)
            //此处的位置需要根据每个分类的集合来进行计算
            var count = 0
            for (i in 0 until position) {
                count += mSortBean.categoryOneArray!![i].categoryTwoArray!!.size
            }
            count += position
            mallAllClassifyFragment.setData(count)
            ItemHeaderDecoration.setAppCurrentTag(targetPosition.toString()) //凡是点击左边，将左边点击的位置作为当前的tag
        } else {
            if (isMoved) {
                isMoved = false
            } else mallAllClassifyTitleAdapter.setCheckedPosition(position)
            ItemHeaderDecoration.setAppCurrentTag(position.toString()) //如果是滑动右边联动左边，则按照右边传过来的位置作为tag
        }
        moveToCenter(position)
    }

    //将当前选中的item居中
    private fun moveToCenter(position: Int) {
        //将点击的position转换为当前屏幕上可见的item的位置以便于计算距离顶部的高度，从而进行移动居中
        val childAt: View = bindingView.recycleView.getChildAt(position - linearLayoutManager.findFirstVisibleItemPosition())
        if (childAt != null) {
            val y: Int = (childAt.top - bindingView.recycleView.height / 2)
            bindingView.recycleView.smoothScrollBy(0, y)
        }
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.theme_color).statusBarDarkFont(false).init()
    }

    override fun isImmersionBarEnabled(): Boolean {
        return true
    }
}